const express = require("express")
const router = express.Router();
const User = require("../controllers/userController")
const userObj = new User()
const Jwt = require("../common/jwt")

router.post("/register", async (req, res) => {
    let { account, password, username, gender, imgUrl } = req.body;
    if (account == undefined || password == undefined || username == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let date = new Date();
        let d1 = date.toLocaleDateString();
        let t1 = date.toLocaleTimeString();
        let createAt = d1 + " " + t1;
        await userObj.register(account, password, username, createAt, gender, imgUrl)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }

})

router.post("/login", async (req, res) => {
    let { account, password } = req.body;
    if (account == undefined || password == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        await userObj.login(account, password)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }

})


router.post("/isLogined", async (req, res) => {
    let token = req.headers.token || req.body.token;
    if (token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            res.status(200).json({ code: 200, msg: "用户登录在线状态", token })
        }
        else {
            res.status(400).json({ code: -1, msg: "用户尚未登录" })
        }
    }
})

router.post("/remove", async (req, res) => {
    let token = req.headers.token
    if (token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            let id = result.info.data;
            await userObj.remove(id)
                .then(
                    result => {
                        res.status(200).json(result);
                    },
                    err => {
                        res.status(500).json(err)
                    }
                )
        }
        else {
            res.status(400).json({ msg: "用户尚未登录" })
        }
    }
})

router.post("/delete", async (req, res) => {
    let { id } = req.body
    let token = req.headers.token || req.body.token

    if (id == undefined) {
        res.status(404).json({ msg: "缺少参数" })
        return
    }

    if (token == undefined) {
        res.status(404).json({ code: -1, msg: "缺少token" })
        return
    }

    // 验证token
    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    // 获取用户ID并验证是否为管理员
    let userId = jwtResult.info.data
    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);
        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以删除用户" })
            return
        }

        // 获取操作者用户名和目标用户信息
        const userInfoSql = 'SELECT username FROM pre_user WHERE id = ?';
        const targetUserSql = 'SELECT username FROM pre_user WHERE id = ?';
        const [operatorInfo, targetUserInfo] = await Promise.all([
            db.query(userInfoSql, [userId]),
            db.query(targetUserSql, [id])
        ]);

        await userObj.remove(id)
            .then(
                async result => {
                    const OperationLog = require("../controllers/operationLogController");
                    const operationLogObj = new OperationLog();
                    const operatorName = operatorInfo[0]?.username || '未知用户';
                    const targetUserName = targetUserInfo[0]?.username || '未知用户';
                    await operationLogObj.add(
                        userId,
                        operatorName,
                        '删除用户',
                        `删除用户：${targetUserName}（ID: ${id}）`
                    ).catch(err => console.error('记录操作日志失败:', err));

                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "删除用户失败", error: error.message })
    }
})

router.post("/items", async (req, res) => {
    let { page_num, page_size } = req.body
    let token = req.headers.token || req.body.token

    if (page_num == undefined || page_size == undefined) {
        res.status(404).json({ code: -1, msg: "缺少参数" })
        return
    }

    if (token == undefined) {
        res.status(401).json({ code: -1, msg: "缺少token，请先登录" })
        return
    }

    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    let userId = jwtResult.info.data

    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);

        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以查看用户列表" })
            return
        }

        await userObj.items(page_num, page_size)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json({ code: -1, msg: "获取用户列表失败", err })
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "验证用户权限失败", error: error.message })
    }
})

router.post("/search", async (req, res) => {
    let { keyword } = req.body
    if (keyword == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        await userObj.search(keyword)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }
})

router.post("/modify", async (req, res) => {
    let { username, gender, imgUrl, id } = req.body
    if (username == undefined || gender == undefined || imgUrl == undefined || id == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        await userObj.modify(username, gender, imgUrl, id)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json(err)
                }
            )
    }
})

router.post("/edit", async (req, res) => {
    let token = req.headers.token
    let { username, gender, imgUrl } = req.body
    if (token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            let id = result.info.data;
            await userObj.modify(username, gender, imgUrl, id)
                .then(
                    result => {
                        res.status(200).json(result);
                    },
                    err => {
                        res.status(500).json(err)
                    }
                )
        }
        else {
            res.status(400).json({ msg: "用户尚未登录" })
        }
    }
})

router.post("/detail", async (req, res) => {
    let { id } = req.body
    let token = req.headers.token
    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            await userObj.detail(id)
                .then(
                    result => {
                        res.status(200).json(result);
                    },
                    err => {
                        res.status(500).json(err)
                    }
                )
        }
        else {
            res.status(400).json({ msg: "您尚未登录" })
        }
    }
})

router.post("/detail2", async (req, res) => {
    let token = req.headers.token
    if (token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
    }
    else {
        let result = new Jwt(token).verifyToken();
        if (result.code == 200) {
            let id = result.info.data
            await userObj.detail(id)
                .then(
                    result => {
                        if (result && result.length > 0) {
                            res.status(200).json({
                                code: 200,
                                msg: "获取用户信息成功",
                                data: result[0]
                            });
                        } else {
                            res.status(404).json({ code: -1, msg: "用户不存在" })
                        }
                    },
                    err => {
                        res.status(500).json({ code: -1, msg: "获取用户信息失败", err })
                    }
                )
        }
        else {
            res.status(400).json({ code: -1, msg: "您尚未登录" })
        }
    }
})

router.post("/mute", async (req, res) => {
    let { id, muteTime } = req.body
    let token = req.headers.token || req.body.token

    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
        return
    }

    // 验证token
    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    // 获取用户ID并验证是否为管理员
    let userId = jwtResult.info.data
    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);
        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以禁言用户" })
            return
        }

        // 检查目标用户是否为管理员
        const targetUserResult = await db.query(sql, [id]);
        if (targetUserResult.length > 0 && targetUserResult[0].role == '1') {
            res.status(403).json({ code: -1, msg: "管理员不可禁言" })
            return
        }

        // 获取操作者用户名和目标用户信息
        const userInfoSql = 'SELECT username FROM pre_user WHERE id = ?';
        const targetUserSql = 'SELECT username FROM pre_user WHERE id = ?';
        const [operatorInfo, targetUserInfo] = await Promise.all([
            db.query(userInfoSql, [userId]),
            db.query(targetUserSql, [id])
        ]);

        await userObj.mute(id, muteTime)
            .then(
                async result => {
                    const OperationLog = require("../controllers/operationLogController");
                    const operationLogObj = new OperationLog();
                    const operatorName = operatorInfo[0]?.username || '未知用户';
                    const targetUserName = targetUserInfo[0]?.username || '未知用户';
                    const muteTimeDesc = muteTime ? `，禁言时长：${muteTime}` : '';
                    await operationLogObj.add(
                        userId,
                        operatorName,
                        '禁言用户',
                        `禁言用户：${targetUserName}（ID: ${id}）${muteTimeDesc}`
                    ).catch(err => console.error('记录操作日志失败:', err));

                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json({ code: -1, msg: "禁言失败", err })
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "禁言失败", error: error.message })
    }
})

router.post("/ban", async (req, res) => {
    let { id } = req.body
    let token = req.headers.token || req.body.token

    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
        return
    }

    // 验证token
    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    // 获取用户ID并验证是否为管理员
    let userId = jwtResult.info.data
    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);
        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以封禁用户" })
            return
        }

        // 检查目标用户是否为管理员
        const targetUserResult = await db.query(sql, [id]);
        if (targetUserResult.length > 0 && targetUserResult[0].role == '1') {
            res.status(403).json({ code: -1, msg: "管理员不可封禁" })
            return
        }

        // 获取操作者用户名和目标用户信息
        const userInfoSql = 'SELECT username FROM pre_user WHERE id = ?';
        const targetUserSql = 'SELECT username FROM pre_user WHERE id = ?';
        const [operatorInfo, targetUserInfo] = await Promise.all([
            db.query(userInfoSql, [userId]),
            db.query(targetUserSql, [id])
        ]);

        await userObj.ban(id)
            .then(
                async result => {
                    const OperationLog = require("../controllers/operationLogController");
                    const operationLogObj = new OperationLog();
                    const operatorName = operatorInfo[0]?.username || '未知用户';
                    const targetUserName = targetUserInfo[0]?.username || '未知用户';
                    await operationLogObj.add(
                        userId,
                        operatorName,
                        '封禁用户',
                        `封禁用户：${targetUserName}（ID: ${id}）`
                    ).catch(err => console.error('记录操作日志失败:', err));

                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json({ code: -1, msg: "封禁失败", err })
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "封禁失败", error: error.message })
    }
})

router.post("/unmute", async (req, res) => {
    let { id } = req.body
    let token = req.headers.token || req.body.token

    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
        return
    }

    // 验证token
    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    // 获取用户ID并验证是否为管理员
    let userId = jwtResult.info.data
    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);
        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以解禁用户" })
            return
        }

        await userObj.unmute(id)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json({ code: -1, msg: "解禁失败", err })
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "解禁失败", error: error.message })
    }
})

router.post("/unban", async (req, res) => {
    let { id } = req.body
    let token = req.headers.token || req.body.token

    if (id == undefined || token == undefined) {
        res.status(404).json({ msg: "缺少参数" })
        return
    }

    // 验证token
    let jwtResult = new Jwt(token).verifyToken();
    if (jwtResult.code != 200) {
        res.status(401).json({ code: -1, msg: "token无效，请重新登录" })
        return
    }

    // 获取用户ID并验证是否为管理员
    let userId = jwtResult.info.data
    const db = require("../common/db/index")
    try {
        const sql = 'SELECT role FROM pre_user WHERE id = ?';
        const userResult = await db.query(sql, [userId]);
        if (userResult.length == 0 || userResult[0].role != '1') {
            res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以解封用户" })
            return
        }

        await userObj.unban(id)
            .then(
                result => {
                    res.status(200).json(result);
                },
                err => {
                    res.status(500).json({ code: -1, msg: "解封失败", err })
                }
            )
    } catch (error) {
        res.status(500).json({ code: -1, msg: "解封失败", error: error.message })
    }
})

module.exports = router;